package handler

import (
	"context"
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/garyburd/redigo/redis"
	"github.com/micro/go-micro/util/log"
	"ihome/models"
	"ihome/utils"

	getUserHouses "ihome/proto/getUserHouses"
)

type GetUserHouses struct{}

func (e *GetUserHouses) SrvGetUserHouses(ctx context.Context, req *getUserHouses.Request, rsp *getUserHouses.Response) error {
	logs.Info("获取用户已发布房源 GetUserHouses /api/v1.0/user/houses")

	rsp.Code = utils.RecodeOk
	rsp.Msg = utils.RecodeText(rsp.Code)

	bm, err := utils.NewCache()
	if err != nil {
		logs.Info("redis连接失败", err)
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}
	sessionId := req.SessionId
	userIdObj := bm.Get(sessionId + "user_id")
	userId, _ := redis.Int(userIdObj, nil)

	o := orm.NewOrm()
	qs := o.QueryTable("house")
	var house_list []models.House

	_, err = qs.Filter("user_id", userId).All(&house_list)

	if err != nil {
		logs.Info("查询房屋信息错误")
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	houses, _ := json.Marshal(house_list)
	rsp.Mix = houses

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *GetUserHouses) Stream(ctx context.Context, req *getUserHouses.StreamingRequest, stream getUserHouses.GetUserHouses_StreamStream) error {
	log.Logf("Received GetUserHouses.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&getUserHouses.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *GetUserHouses) PingPong(ctx context.Context, stream getUserHouses.GetUserHouses_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&getUserHouses.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
